package com.kkb.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kkb.mapper.DrugMapper;
import com.kkb.pojo.DoctorExample;
import com.kkb.pojo.Drug;
import com.kkb.pojo.DrugExample;
import com.kkb.vo.DrugQueryVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class DrugService {

    @Resource
    DrugMapper mapper;

    public List queryAll() {
        return mapper.selectByExample(null);
    }

    public PageInfo<Drug> selectInPage(Integer index, Integer size, DrugQueryVO vo) {
        if ("".equals(vo.getName().trim())){
            vo.setName(null);
        }
        if ("".equals(vo.getType().trim())){
            vo.setType(null);
        }
        PageHelper.startPage(index,size);
        List<Drug> list = mapper.selectByVo(vo);
        return new PageInfo<>(list);
    }

    public Drug selectById(Integer id){
        return mapper.selectByPrimaryKey(id);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public int insertDrug(Drug drug){
        return mapper.insertSelective(drug);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public int updateStock(Integer id, Integer increase){
        Drug drug = mapper.selectByPrimaryKey(id);
        Integer stock = drug.getStock() != null ? drug.getStock(): 0;
        stock += increase;
        drug.setStock(stock);
        return mapper.updateByPrimaryKeySelective(drug);
    }
}
